package xyc.sjxy.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Base64;
import java.util.Date;

public class JwtUtils {
    private static final String JWT_SECRET = "7Fey68PZw19Xc1DtNSv4N0IgZXxr97jj";// 密钥
    private static final String JWT_PREFIX = "Bearer ";
    private static final Key signingKey = Keys.hmacShaKeyFor(JWT_SECRET.getBytes(StandardCharsets.UTF_8));// 生成签名密钥

    public static String createJwt(String username, String password) {
        String jwt = Jwts.builder().issuer("zjl--issuer").// 设置发行人
                subject("token-subject").// 设置主题
                claim("username", username).// 设置自定义的Claims
                //claim("password", password).// 设置自定义的Claims
                signWith(signingKey).// 设置签名算法和密钥
                expiration(new Date(System.currentTimeMillis() + 1000 * 60*10)). // 设置过期时间为1小时
                compact();
        return JWT_PREFIX + jwt;
    }

    public static String validateJwt(String jwt) {// 验证JWT
        String username;
        try {
            Jws<Claims> claims = Jwts.parser().// 设置签名密钥
                    verifyWith((SecretKey) signingKey).// 设置签名算法和密钥
                    build().// 验证签名并返回Claims对象
                    parseSignedClaims(jwt.substring(7));// 解析JWT字符串并返回Claims对象
            if (claims != null && claims.getPayload().containsKey("username")) {
                username = (String) claims.getPayload().get("username");// 获取自定义的Claims
            } else {
                throw new IllegalArgumentException("Username is missing.");// 用户名缺失 抛出异常
            }
        } catch (ExpiredJwtException e) {
            throw new RuntimeException("Token has expired", e);// 过期Token 抛出异常
        } catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException e) {
            throw new RuntimeException("Invalid Token", e);// 非法Token 抛出异常
        }catch (Exception e) {
            throw new RuntimeException("Token Error", e);// 非法Token 抛出异常
        }
        return username;
    }

    public static String base64Encode(String str) {
        return Base64.getEncoder().encodeToString(str.getBytes(StandardCharsets.UTF_8));
    }

    public static String base64Decode(String str) {
        return new String(Base64.getDecoder().decode(str), StandardCharsets.UTF_8);
    }
}
